package com.cskaoyan.user.service.impl;

import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.UserLogoutResponse;
import com.cskaoyan.user.service.UserLogoutService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sosog
 * @version 1.0.0
 * @description TODO
 * @date 2022/6/20 13:47
 */
@Slf4j
@Service
public class UserLogoutServiceImpl implements UserLogoutService {
    @Override
    public UserLogoutResponse logout(HttpServletRequest request, HttpServletResponse servletResponse) {
        UserLogoutResponse response = new UserLogoutResponse();
        Cookie[] cookies = request.getCookies();
        if (ArrayUtils.isNotEmpty(cookies)) {
            for (Cookie cookie : request.getCookies()) {
                if (StringUtils.equals("access_token", cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    servletResponse.addCookie(cookie);
                    response.setCode(UserRetCode.SUCCESS.getCode());
                    response.setMsg(UserRetCode.SUCCESS.getMessage());
                    return response;
                }
            }
        }
        log.info("cookie清除失败");
        response.setCode(UserRetCode.SYSTEM_ERROR.getCode());
        response.setMsg(UserRetCode.SYSTEM_ERROR.getMessage());
        return response;
    }
}
